package cn.laixueit.service.impl;

import cn.laixueit.mapper.ClassesMapper;
import cn.laixueit.pojo.Classes;
import cn.laixueit.pojo.ClassesExample;
import cn.laixueit.service.ClassesService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassesMapper classesMapper;

    @Override
    public void save(Classes classes) {
        if(classes.getOpen() == 1){
            classes.setOpendate(new Date());
        }
        classesMapper.insertSelective(classes);
    }

    @Override
    public void update(Classes classes,Integer close) {
        if(1 == close){
            classes.setEnddate(new Date());
        }
        classesMapper.updateByPrimaryKeySelective(classes);
    }

    @Override
    public void removeById(Integer id) {
        classesMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Classes findById(Integer id) {
        Classes classes = classesMapper.selectByPrimaryKey(id);
        return classes;
    }

    @Override
    public PageInfo<Classes> page(Integer start, Integer size, Classes classes) {
        PageHelper.startPage(start,size);
        List<Classes> classesList = classesMapper.selectByExample(getExample(classes));
        PageInfo<Classes> pageInfo = new PageInfo<>(classesList);
        return pageInfo;
    }

    @Override
    /**
     * 查询所有班级，条件已经开班的没有结班的
     */
    public List<Classes> findClassList() {
        Classes classes = new Classes();
        classes.setOpen(1);
        classes.setEnddate(null);
        ClassesExample example = getExample(classes);
        List<Classes> classesList = classesMapper.selectByExample(example);
        return classesList;
    }

    @Override
    public List<Classes> findAllClassList() {
        return classesMapper.selectByExample(null);
    }

    private ClassesExample getExample(Classes classes){
        ClassesExample example = new ClassesExample();
        ClassesExample.Criteria criteria = example.createCriteria();
        if(classes!=null){
            if(!StringUtils.isEmpty(classes.getName())){
                criteria.andNameLike("%"+classes.getName()+"%");
            }
            if(classes.getOpendate() != null){
                criteria.andOpendateGreaterThanOrEqualTo(classes.getOpendate());
            }
            if(classes.getOpen() != null){
                criteria.andOpenEqualTo(classes.getOpen());
            }
            if(classes.getEnddate() == null){
                criteria.andEnddateIsNull();
            }
        }
        return example;
    }
}
